package zhr.store.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import zhr.store.common.Result;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * 文件上传及下载
 */
@RestController
@RequestMapping("/common")
public class CommonController {
    @Value("${app.path}")
    private String path;

    /**
     * 文件上传
     *
     * @return
     */
    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file) throws IOException {
        //获取文件名称
        String originalFilename = file.getOriginalFilename();
        //文件转存本地
        file.transferTo(new File(path + originalFilename));
        return Result.success(originalFilename);
    }

    /**
     * 文件下载
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) throws IOException {
        //输入流读取
        FileInputStream inputStream = new FileInputStream(new File(path + name));
        //输出流展示
        ServletOutputStream outputStream = response.getOutputStream();
        response.setContentType("/imag/jpeg");
        int length = 0;
        byte bytes[] = new byte[1024];
        while ((length = inputStream.read(bytes)) != -1) {
            outputStream.write(bytes, 0, length);
            outputStream.flush();
        }
        //关闭
        inputStream.close();
        outputStream.close();
    }
}
